package com.example.demo.config;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
@Slf4j
@Component
@ComponentScan("com.example.demo.controller.test")
public class DateConverter implements Converter<String  ,Date> {

private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";

private static final String shortDateFormat = "yyyy-MM-dd";

private static final String timeStampFormat = "^\\d+$";

private static final String hDateFormat = "yyyy年MM月dd日 HH:mm:ss";

private static final String hshortDateFormat = "yyyy年MM月dd日";

private static final String dateFormat_REG ="^((\\d{4}(-)\\d{1,2}(-)\\d{1,2}))(\\s)\\d{1,2}:\\d{1,2}:\\d{1,2}$";

    private static final String shortDateFormat_REG = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})" +
            "-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|" +
            "((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)";

    @Override
    public Date convert(String value) {
        if (StringUtils.isBlank(value)) {
            return null;

        }
        value = value.trim();
        SimpleDateFormat formatter;
        try {
            if (value.matches(dateFormat_REG)) {

                formatter = new SimpleDateFormat(dateFormat);
                return formatter.parse(value);

            } else if (value.matches(shortDateFormat_REG)) {
                formatter = new SimpleDateFormat(shortDateFormat);

                return formatter.parse(value);

            } else{
                log.error("当前日期格式不匹配，日期值为{}",value);
            }

        } catch (Exception e) {
            throw new RuntimeException(String.format("parser %s to Date fail", value));

        }
        return null;
    }
}
